using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Comteck.Winforms.Json {
  /// <summary>
  /// DateOnly的转换
  /// </summary>
  public class DateOnlyConverter : IsoDateTimeConverter {

    public override bool CanConvert(Type objectType) {
      if (objectType == typeof(DateOnly) || objectType == typeof(DateOnly?)) {
        return true;
      }

      return false;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
      var date = base.ReadJson(reader, objectType, existingValue, serializer) as DateTime?;

      if (date.HasValue) {
        return DateOnly.FromDateTime(date.Value);
      }

      return null;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
      var date = value as DateOnly?;
      value = date ?? value;
      string text = null;
      if (value is DateOnly dateOnly) {
        text = dateOnly.ToString("yyyy-MM-dd", this.Culture);
      }

      writer.WriteValue(text);
    }

  }
}
